<?php
namespace app\common\model;
use think\Model;
use think\model\concern\SoftDelete;

class SysManagerModel extends BaseModel
{
    use SoftDelete;
    protected $table = 'sys_manager';
    /**
     * //用户登录模型
     * @var self
     * */
    public static $login_user_model=null;

    public function getGroupCateIdAttr($value,$data)
    {
        $cid = $data['rid']??'';
        $ct_id = $data['rt_id']??'';
        $str = empty($cid)?'':$cid;
        if(!empty($ct_id)){
            $str .= ','.$ct_id;
        }
        return $str;
    }

    public function setPasswordAttr($value)
    {
        $salt = rand(1000,9999);
        $this->setAttr('salt',$salt);
        return self::generatePwd($value,$salt);
    }

    public function getLastTimeAttr($value)
    {
        return empty($value)?'':date('Y-m-d H:i:s',$value);
    }

    //删除前操作
    public static function onBeforeDelete(Model $model)
    {
        if($model->is_special){
            throw new \Exception('系统指定角色无法删除');
        }
    }

    /**
     * 管理员登录
     * @param $php_input array 数组
     * *@throws
     * @return array|self
     */
    public static function login(array $php_input=[]){
        $account = $php_input['account']??'';
        $password = $php_input['password']??'';
        $verify = $php_input['verify']??'';
//        dump($_SESSION);
//        dump($verify);exit;
//        if (!captcha_check($verify)) throw new \Exception('验证码错误');
        if (!isset($php_input['is_chat']) && !captcha_check($verify)) throw new \Exception('验证码错误');
        if (empty($account))  throw new \Exception('用户名不能为空');
        if (empty($password ))  throw new \Exception('密码不能为空');
        $model = self::where('account',$account)->find();
        if (!$model)  throw new \Exception('请检查账号是否正确');
        $status = $model['status'];
        if ($status!=1) throw new \Exception('该账号已停用');
        //判断密码是否正确
        if(self::generatePwd($password,$model['salt'])!=$model->password) throw new \Exception('用户名或密码错误');

        if(isset($php_input['is_chat']) && $model['is_chat']!=$php_input['is_chat'])  throw new \Exception('只有聊天客服才能登录');

        //最后一次登陆时间
        $model->last_time = time();
        //登陆ip
        $model->last_login_ip = app()->request->ip();
        //登陆次数
        $model->login_times = $model->login_times+1;
        $model->save();

        return $model;
    }

    /**
     * 获取列表
     * @param array  $input_data
     * @throws
     * @return \think\Paginator
     * */
    public static function getPageData(array $input_data = [])
    {
        $limit = $input_data['limit']??null;

        $where = [];
        $keyword = trim($input_data['keyword']??'');
        !empty($keyword) && $where[] = ['name|account','like','%'.$keyword.'%'];
        return self::with(['linkRole','linkRole2'])->where($where)->paginate($limit);
    }



    public static function handleSaveData(array $input_data = [])
    {
        if(empty($input_data['name'])) throw new \Exception('请输入管理员名字');
        if(empty($input_data['account'])) throw new \Exception('请输入管理员帐号');

        $group_cid=empty($input_data['group_cate_id'])?[]:explode(',',$input_data['group_cate_id']);
        $input_data['rid'] = $group_cid[0]??0;
        $input_data['rt_id'] = $group_cid[1]??0;

        if(!empty($input_data['password'])){
            if(strlen($input_data['password'])<6) throw new \Exception('请输入管理员密码长度不得低于6位');
        }elseif(empty($input_data['id']) && empty($input_data['password'])){
            if(empty($input_data['password'])) throw new \Exception('请输入管理员密码');
        }else{
            unset($input_data['password']);
        }
        $where = [];
        $where[] = ['account','=',$input_data['account']];
        if(!empty($input_data['id'])){
            $where[] = ['id','<>',$input_data['id']];
        }
        if(self::where($where)->find()) throw new \Exception('帐号已被使用,请更换帐号');
        (new self())->actionAdd($input_data);
    }




    //获取信息
    public function apiNormalInfo()
    {
        $linkRole =  $this->getRelation('linkRole');
        $linkRole2 =  $this->getRelation('linkRole2');
        $status = $this['status'];
        return [
            'id'=>$this['id'],
            'account'=>$this['account'],
            //分类
            'group_cate_id' => (string)$this['group_cate_id'],

            'rid'=>(string)$linkRole['id'],
            'role_name'=>(string)$linkRole['name'],
            'rid2'=>(string)$linkRole2['id'],
            'role2_name'=>(string)$linkRole2['name'],
            'name'=>$this['name'],
            'status'=> $status,
            'status_name'=>self::getPropInfo('fields_status',$status,'name'),
        ];
    }



    //角色
    public function linkRole()
    {
        return $this->belongsTo(SysRoleModel::class,'rid');
    }
    //角色
    public function linkRole2()
    {
        return $this->belongsTo(SysRoleModel::class,'rt_id');
    }
}